<template>
  <div class="order-statistics">
    <a-alert
      type="warning"
      message="只统计订单成交和挂单未成交的订单，已取消、已关闭不统计"
      showIcon
      banner
    ></a-alert>
    <div class="filtrate layout-content">
      <!-- <c-desc :columns="filtrateCols" :column="1" :labelStyle="{width: '80px',textAlign: 'right'}"> -->
      <c-form
        :data="formData"
        :col="{ labelCol: { style: { width: '90px', marginBottom: '10px' } } }"
      >
        <template v-slot:date>
          <!-- <c-tags-check :data="dateTags" :defaultValue="[1]"/> -->
          <!-- <a-radio-group v-model="params.date" button-style="solid">
            <a-radio-button
              :value="item.value"
              v-for="item in dateTags"
              :key="item.value"
            >
              {{ item.title }}
            </a-radio-button>
          </a-radio-group> -->
          <a-range-picker
            v-model="params.date"
            :allowClear="false"
            @change="
              (date, dateString) => {
                dateChange(date, dateString, 'change');
              }
            "
            @ok="
              (date, dateString) => {
                dateChange(date, dateString, 'ok');
              }
            "
            :showTime="{
              defaultValue: [
                momentTime('00:00:00', 'HH:mm:ss'),
                momentTime('23:59:59', 'HH:mm:ss')
              ]
            }"
            valueFormat="x"
          />
        </template>
        <!-- <template v-slot:condition>
          <a-select v-model="params.condition" style="width: 200px">
            <a-select-option :value="1">按品种汇总查询</a-select-option>
            <a-select-option :value="2">自定义查询</a-select-option>
          </a-select>
        </template> -->
        <template v-slot:category>
          <c-category
            v-model="params.categoryCode"
            :allowClear="false"
            :extra="[
              {
                id: 0,
                categoryType: 0,
                categoryName: '按品种汇总'
              }
            ]"
            @change="searchCategory"
            style="width: 200px"
          />
        </template>
        <template v-slot:company>
          <c-deal-company
            v-model="params.company"
            :allowClear="false"
            :extra="[
              {
                companyId: '',
                companyName: '按交易公司汇总'
              }
            ]"
            @change="searchCompany"
          />
        </template>
        <template v-slot:priceType>
          <c-tags-check
            :data="pricingTypeTags"
            :defaultValue="[0]"
            @change="searchPricingType"
          />
          <!-- <a-radio-group v-model="params.priceType" button-style="solid">
            <a-radio-button
              :value="item.value"
              v-for="item in pricingTypeTags"
              :key="item.value"
            >
              {{ item.title }}
            </a-radio-button>
          </a-radio-group> -->
        </template>
        <template v-slot:orderStatus>
          <c-tags-check
            :data="orderStatusTags"
            :defaultValue="[0]"
            @change="searchOrderStatus"
          />
          <!-- <a-radio-group v-model="params.orderStatus" button-style="solid">
            <a-radio-button
              :value="item.value"
              v-for="item in orderStatusTags"
              :key="item.value"
            >
              {{ item.title }}
            </a-radio-button>
          </a-radio-group> -->
        </template>
      </c-form>
      <!-- </c-desc> -->
    </div>
    <div class="content layout-content">
      <c-table
        :data="tableData"
        :columns="columns"
        :scroll="{ y: 800 }"
        :rowClassName="
          () => {
            return 'main-table-row';
          }
        "
        bordered
        :outerborder="false"
        :loading="loading"
        @onReload="reload"
      >
        <template v-slot:categoryId="{ row }">
          {{ getCategoryId(row.categoryId, { value: "categoryName" })[1] }}
        </template>
        <template slot="footer">
          <c-table
            v-if="tableFootData.length !== 0"
            ref="tableFoot"
            :rowClassName="
              () => {
                return 'foot-table-row';
              }
            "
            :data="tableFootData"
            :columns="tableFootColumns"
            :outerborder="false"
            :showHeader="false"
            :showTableHeader="false"
          ></c-table>
        </template>
      </c-table>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import { queryordersummary } from "@/api/order/statistics";
import { getCategoryId } from "@/util/common";

export default {
  data() {
    return {
      dateDefaultValue: [],
      dateTags: [
        {
          title: "当天",
          value: 1
        },
        {
          title: "当周",
          value: 2
        },
        {
          title: "当月",
          value: 3
        }
      ],
      pricingTypeTags: [
        {
          title: "全部",
          value: 0
        },
        {
          title: "点价",
          value: 1
        },
        {
          title: "确定价",
          value: 2
        }
      ],
      orderStatusTags: [
        {
          title: "全部",
          value: 0
        },
        {
          title: "待挂单",
          value: 1
        },
        {
          title: "已挂单",
          value: 2
        },
        {
          title: "待生成合同",
          value: 3
        },
        {
          title: "已生成合同",
          value: 4
        }
      ],
      params: {
        date: 1,
        categoryCode: [0],
        company: "",
        // condition: 1,
        priceType: undefined,
        orderStatus: [1, 2, 3, 4, 5, 7, 9, 10, 11, 12, 13]
      },
      filtrateCols: [
        {
          label: "时间",
          slot: "date"
        },
        {
          label: "作价方式",
          slot: "priceType"
        },
        {
          label: "订单状态",
          slot: "orderStatus"
        },
        {
          label: "商品种类",
          slot: "category"
        },
        {
          label: "交易公司",
          slot: "company"
        }
      ],
      loading: false,
      tableData: [],
      tableFootData: [],
      tableFootColumnsWidth: [],
      columns: [
        {
          title: "交易公司",
          dataIndex: "companyName"
        },
        {
          title: "商品种类",
          // dataIndex: "categoryId",
          scopedSlots: { customRender: "categoryId" }
          // width: 100
        },
        {
          title: "下单数",
          dataIndex: "amount"
          // width: 100
        },
        {
          title: "成交数",
          dataIndex: "dealAmount"
          // width: 100
        },
        {
          title: "订单超量总数",
          dataIndex: "overAmount"
          // width: 150
        },
        {
          title: "订单可关联数",
          dataIndex: "availableRelationAmount"
          // width: 150
        },
        {
          title: "订单已关联数",
          dataIndex: "alreadyRelationAmount"
          // width: 150
        }
      ]
    };
  },
  computed: {
    formData() {
      return [
        {
          label: "时间",
          slot: "date"
        },
        {
          label: "商品种类",
          slot: "category"
        },
        {
          label: "交易公司",
          slot: "company"
        },
        {
          label: "作价方式",
          slot: "priceType"
        },
        {
          label: "订单状态",
          slot: "orderStatus"
        }
        // {
        //   label: "统计条件",
        //   slot: "condition"
        // },
      ];
    },
    tableFootColumns() {
      let res = JSON.parse(JSON.stringify(this.columns));
      res.forEach((item, idx) => {
        if (idx === 0) return;
        item.width = this.tableFootColumnsWidth[idx];
      });
      return res;
    }
  },
  methods: {
    getCategoryId,
    moment,
    momentTime(time, format) {
      return moment(time, format);
    },
    // 选择日期
    dateChange(date, dateString, type) {
      if (
        this.params.date[1] - this.params.date[0] >
        1000 * 60 * 60 * 24 * 31
      ) {
        this.$message.warning("日期可选最大区间为一个月");
        this.params.date = [];
        return;
      }
      if (type === "change" && date.length === 0) return;
      this.init();
    },
    setDateDateDefaultValue() {
      let date = moment().format("YYYY-MM-DD");
      this.params.date = [
        moment(date + " 00:00:00").format("x"),
        moment(date + " 23:59:59").format("x")
      ];
      this.init();
    },
    reload() {
      this.init();
    },
    searchCompany() {
      this.reload();
    },
    searchDate() {
      this.init();
    },
    searchPricingType(val) {
      this.params.priceType = val[0] === 0 ? undefined : val[0];
      this.reload();
    },
    searchOrderStatus(val) {
      switch (val[0]) {
        case 0:
          this.params.orderStatus = [1, 2, 3, 4, 5, 7, 9, 10, 11, 12, 13, 16];
          break;
        case 1:
          this.params.orderStatus = [1];
          break;
        case 2:
          this.params.orderStatus = [2, 9, 10, 13];
          break;
        case 3:
          this.params.orderStatus = [3, 4, 5, 11, 12, 16];
          break;
        case 4:
          this.params.orderStatus = [7];
          break;
        default:
          break;
      }
      this.reload();
    },
    searchCategory() {
      this.reload();
    },
    // 计算总数
    sum(data) {
      // return new Promise(resolve => {
      let amount = 0;
      let dealAmount = 0;
      let availableRelationAmount = 0;
      let alreadyRelationAmount = 0;
      let overAmount = 0;
      data.forEach(item => {
        amount += item.amount;
        dealAmount += item.dealAmount;
        availableRelationAmount += item.availableRelationAmount;
        alreadyRelationAmount += item.alreadyRelationAmount;
        overAmount += item.overAmount;
      });
      this.tableFootData = [
        // ...data,
        {
          companyName: "合计",
          amount: this.$tools.formatFloat(amount),
          dealAmount: this.$tools.formatFloat(dealAmount),
          availableRelationAmount: this.$tools.formatFloat(
            availableRelationAmount
          ),
          alreadyRelationAmount: this.$tools.formatFloat(alreadyRelationAmount),
          overAmount: this.$tools.formatFloat(overAmount)
        }
      ];
      this.$nextTick(() => {
        let a = document.getElementsByClassName("main-table-row")[0];
        let ele = a.getElementsByTagName("td");
        let length = ele.length;
        this.$refs.tableFoot.$el.style.width = a.offsetWidth + 1 + "px";
        this.tableFootColumnsWidth = [];
        for (let i = 0; i < length; i++) {
          this.tableFootColumnsWidth.push(ele[i].offsetWidth);
        }
      });
      // resolve(res)
      // })
    },
    init() {
      this.loading = true;
      queryordersummary({
        startTime: this.params.date[0],
        endTime: this.params.date[1],
        customerCompanyId:
          this.params.company === "" ? undefined : this.params.company,
        categoryId:
          this.params.categoryCode.length === 1
            ? undefined
            : this.params.categoryCode[1],
        priceType: this.params.priceType,
        orderStatuses: this.params.orderStatus
      })
        .then(res => {
          this.tableData = [];
          this.tableFootData = [];
          if (res) {
            this.tableData = res;
            this.sum(res);
            // this.sum(res).then(data => {
            //   this.tableData = data
            // })
          }
        })
        .finally(() => {
          this.loading = false;
        });
    }
  },
  created() {
    this.setDateDateDefaultValue();
  }
};
</script>

<style lang="scss" scoped>
.order-statistics {
  ::v-deep .ant-form-item {
    margin-bottom: 0;
  }
  ::v-deep .ant-table.ant-table-bordered .ant-table-footer {
    border: 0;
  }
  ::v-deep .ant-table-footer {
    padding: 0 !important;
    .foot-table-row td {
      background-color: #fafafa;
    }
  }
}
</style>
